package com.haojiang.mh.remote.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CompoundButton;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.haojiang.mh.AppContext;
import com.haojiang.mh.R;
import com.haojiang.mh.remote.bean.BleRssiDevice;
import com.haojiang.mh.remote.bean.ConnectGroup;
import com.haojiang.mh.remote.bean.ConnectKey;
import com.haojiang.mh.remote.bean.ConnectValue;
import com.haojiang.mh.remote.enums.EConnect;
import com.haojiang.mh.remote.enums.EStep;
import com.haojiang.mh.remote.event.ConnectEvent;
import com.haojiang.mh.remote.event.ShowBleEvent;
import com.haojiang.mh.remote.ui.dialog.ModifyDialogFrag;
import com.haojiang.mh.remote.ui.dialog.RoundCornerDialog;
import com.haojiang.mh.remote.utils.BleUtil;
import com.haojiang.mh.remote.utils.LogUtil;
import com.haojiang.mh.remote.utils.Util;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static android.view.View.VISIBLE;

public class GroupExpandableListViewAdapter extends BaseExpandableListAdapter {


    private List<ConnectGroup> mBleGroupList = new ArrayList<ConnectGroup>();
    private ExpandableListView mExpandableListView;
    private FragmentActivity mFm;

    public GroupExpandableListViewAdapter(FragmentActivity fm, ExpandableListView expandableListView) {
        mFm = fm;
        mExpandableListView = expandableListView;
    }

    public void setData(Map<String, ConnectGroup> bleGroupMap) {
        if (bleGroupMap == null || bleGroupMap.size() == 0) return;
        mBleGroupList.clear();
        for (Map.Entry<String, ConnectGroup> entry : bleGroupMap.entrySet()) {
            ConnectGroup bleGroup = entry.getValue();
            if (bleGroup != null && bleGroup.getConnectKey() != null) {
                mBleGroupList.add(bleGroup);
            }
        }
//        mBleGroupList.sort(new Comparator<BleGroup>() {
//            @Override
//            public int compare(BleGroup o1, BleGroup o2) {
//                return (int) (o1.getGroupKey().getId() - o2.getGroupKey().getId());
//            }
//        });

        Collections.sort(mBleGroupList);
        notifyDataSetChanged();
    }


    @Override
    public int getGroupCount() {
        return mBleGroupList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return mBleGroupList.get(groupPosition).getConnectValueList().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return mBleGroupList.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return mBleGroupList.get(groupPosition).getConnectValueList().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return groupPosition + childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }


    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {

        GroupViewHolder groupViewHolder;
        if (convertView == null) {
            convertView = View.inflate(parent.getContext(), R.layout.item_group, null);
            groupViewHolder = new GroupViewHolder(convertView);
            convertView.setTag(groupViewHolder);
        } else {
            groupViewHolder = (GroupViewHolder) convertView.getTag();
        }

        ConnectGroup bleGroup = mBleGroupList.get(groupPosition);
        ConnectKey groupKey = bleGroup.getConnectKey();
        ArrayList<ConnectValue> groupValueList = bleGroup.getConnectValueList();

        LogUtil.e(groupKey + "====================??");

//        if (groupKey != null) {
//        }

        groupViewHolder.tvGroupName.setText(groupKey.getName());
        if (groupKey.getType() == EConnect
                .CONNECT_GROUP_SINGLE.getData()) {
            groupViewHolder.ivIcon.setImageResource(R.drawable.ic_group_single_n);
            groupViewHolder.tvGroupType.setText(AppContext.Companion.instance().getString(R.string.f_single_control));
//            groupViewHolder.tvGroupType.setText(AppContext.instance().getString(R.string.f_single_control));
            if (groupValueList.size() <= 0) {
                groupViewHolder.ivAdd.setVisibility(VISIBLE);

            } else {
                groupViewHolder.ivAdd.setVisibility(View.INVISIBLE);
            }
        } else if (groupKey.getType() == EConnect
                .CONNECT_GROUP_MULTIPLE.getData()) {
            groupViewHolder.ivIcon.setImageResource(R.drawable.ic_group_multiple_n);
            groupViewHolder.tvGroupType.setText(AppContext.Companion.instance().getString(R.string.f_multiple_control));
//            groupViewHolder.tvGroupType.setText(AppContext.instance().getString(R.string.f_multiple_control));
            if (groupValueList.size() <= 6) {
                groupViewHolder.ivAdd.setVisibility(VISIBLE);
            } else {
                groupViewHolder.ivAdd.setVisibility(View.INVISIBLE);
            }
        } else if (groupKey.getType() == EConnect
                .CONNECT_GROUP_SPLIT.getData()) {
            groupViewHolder.ivIcon.setImageResource(R.drawable.ic_group_split_n);
            groupViewHolder.tvGroupType.setText(AppContext.Companion.instance().getString(R.string.f_spilit_control));
//            groupViewHolder.tvGroupType.setText(AppContext.instance().getString(R.string.f_spilit_control));
            if (groupValueList.size() <= 0) {
                groupViewHolder.ivAdd.setVisibility(VISIBLE);
            } else {
                groupViewHolder.ivAdd.setVisibility(View.INVISIBLE);
            }
        }
        groupViewHolder.setEvent(convertView, groupKey, groupValueList);
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

        ChildViewHolder childViewHolder;
        if (convertView == null) {
            convertView = View.inflate(parent.getContext(), R.layout.item_child, null);
            childViewHolder = new ChildViewHolder(convertView);
            convertView.setTag(childViewHolder);
        } else {
            childViewHolder = (ChildViewHolder) convertView.getTag();
        }
        ConnectGroup bleGroup = mBleGroupList.get(groupPosition);
        String bleAddress = bleGroup.getConnectValueList().get(childPosition).getBleRssiDevice().getBleAddress();
//        LogUtil.e(bleAddress);
//        String InterfaceNo = BleUtil.Companion.readSingleInterfaceNo(bleAddress);
//        if(TextUtils.isEmpty(InterfaceNo)) {
//            InterfaceNo = bleGroup.getGroupValueList().get(childPosition).getBleRssiDevice().getDeviceAlias();
//        }
        String InterfaceNo = bleGroup.getConnectValueList().get(childPosition).getBleRssiDevice().getDeviceAlias();
        childViewHolder.tvChildName.setText(InterfaceNo);
        childViewHolder.tvChildAddress.setText(bleAddress);
        childViewHolder.setEvent(bleGroup, childPosition, convertView);
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    private int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 展示删除的dialog（可以自定义弹窗，不用删除即可）
     *
     * @param
     */
    private void showDeleteDialog(Context context) {
        View view = View.inflate(context, R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(context, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
//        WindowManager.LayoutParams params = Objects.requireNonNull(roundCornerDialog.getWindow()).getAttributes();
//        params.width = dip2px(context, 350);
//        roundCornerDialog.getWindow().setAttributes(params);
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        roundCornerDialog.setOnKeyListener(keylistener);//设置点击返回键Dialog不消失


        TextView tvMessage = view.findViewById(R.id.tvMessage);
        TextView tvConfirm = view.findViewById(R.id.tvConfirm);
        TextView tvCancel = view.findViewById(R.id.tvCancel);
        tvMessage.setText(context.getString(R.string.m_delete_confirm));

        //确定
        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int curGroupPos = -1;
                //删除当前选中的整个组
                for (int i = 0; i < mBleGroupList.size(); i++) {
                    mExpandableListView.collapseGroup(i);
                    if (mBleGroupList.get(i).getConnectKey().isSelect()) {
                        BleUtil.deleteGroupKey(mBleGroupList.get(i).getConnectKey());
                        mBleGroupList.remove(i);
                        break;
                    } else {
                        ArrayList<ConnectValue> groupValueList = mBleGroupList.get(i).getConnectValueList();
                        boolean isRemove = false;
                        for (int j = 0; j < groupValueList.size(); j++) {
                            if (groupValueList.get(j).isSelect()) {
                                isRemove = true;
                                curGroupPos = i;
                                groupValueList.remove(j);
                            }
                        }
                        if (isRemove) {
                            BleUtil.deleteGroupValueList(mBleGroupList.get(i).getConnectKey().getId() + "", groupValueList);
                        }
                    }
                }
                notifyDataSetChanged();
                if (curGroupPos != -1) {
                    mExpandableListView.expandGroup(curGroupPos, true);
                }
                roundCornerDialog.dismiss();
            }
        });

        //取消
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                return true;
            } else {
                return false;
            }
        }
    };

    public void add() {

    }


    public void delete(Context context) {
        int expandableIndex = -1;
        for (int i = 0; i < mBleGroupList.size(); i++) {
            mExpandableListView.collapseGroup(i);
            if (mBleGroupList.get(i).getConnectKey().isSelect()) {
                expandableIndex = i;
            } else {
                for (ConnectValue groupValue : mBleGroupList.get(i).getConnectValueList()) {
                    if (groupValue.isSelect()) {
                        expandableIndex = i;
                        break;
                    }
                }
            }
        }
        if (expandableIndex != -1) {
            mExpandableListView.expandGroup(expandableIndex, true);
            showDeleteDialog(context);
        } else {
            Toast.makeText(context, context.getString(R.string.m_no_select_item), Toast.LENGTH_SHORT);
        }
    }

    //恢复到未选择状态
    private void traverseSelector(ConnectKey groupKey) {
        for (int i = 0; i < mBleGroupList.size(); i++) {
            if (mBleGroupList.get(i).getConnectKey().equals(groupKey)) {
                mExpandableListView.expandGroup(i, true);
            } else {
                mBleGroupList.get(i).getConnectKey().setSelect(false);
                for (ConnectValue groupValue : mBleGroupList.get(i).getConnectValueList()) {
                    groupValue.setSelect(false);
                }
                mExpandableListView.collapseGroup(i);
            }
        }
    }

    public void modifyItem(@NotNull String bleAddress, @NotNull String deviceAlias) {
        for (int i = 0; i < mBleGroupList.size(); i++) {
            ArrayList<ConnectValue> groupValueList = mBleGroupList.get(i).getConnectValueList();
            for (int j = 0; j < groupValueList.size(); j++) {
                if (groupValueList.get(j).getBleRssiDevice().getBleAddress().equals(bleAddress)) {
                    groupValueList.get(j).getBleRssiDevice().setDeviceAlias(deviceAlias);
                    break;
                }
            }
        }
        notifyDataSetChanged();
    }

    class GroupViewHolder {

        private ImageView ivGroupSelector;
        private ImageView ivIcon;
        private TextView tvGroupType;
        private TextView tvGroupName;
        private ImageView ivAdd;
        private TextView tvConnect;

        GroupViewHolder(View view) {
            ivGroupSelector = view.findViewById(R.id.ivGroupSelector);
            ivIcon = view.findViewById(R.id.ivIcon);
            tvGroupType = view.findViewById(R.id.tvGroupType);
            tvGroupName = view.findViewById(R.id.tvGroupName);
            ivAdd = view.findViewById(R.id.ivAdd);
            tvConnect = view.findViewById(R.id.tvConnect);
        }

        void setEvent(View convertView, final ConnectKey groupKey, final ArrayList<ConnectValue> groupValueList) {
            changeGroupSelector(groupKey);

            ivGroupSelector.setOnClickListener(v -> {
                //恢复默认值
                traverseSelector(groupKey);

                //判断选择值
                if (groupKey.isSelect()) {
                    ivGroupSelector.setImageResource(R.drawable.ic_unselect);
                } else {
                    ivGroupSelector.setImageResource(R.drawable.ic_select);
                }
                groupKey.setSelect(!groupKey.isSelect());
                boolean isSelect = groupKey.isSelect();
                for (int i = 0; i < mBleGroupList.size(); i++) {
                    ConnectGroup bleGroup = mBleGroupList.get(i);
                    if (bleGroup.getConnectKey().equals(groupKey)) {
                        bleGroup.getConnectKey().setSelect(isSelect);
                        for (ConnectValue groupValue : bleGroup.getConnectValueList()) {
                            groupValue.setSelect(isSelect);
                        }
                        break;
                    }
                }
                notifyDataSetChanged();
            });


            //子选项添加
            ivAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EventBus.getDefault().post(new ShowBleEvent(groupKey.getType(), groupKey.getId()));
                }
            });

            //多个设备发送
            tvConnect.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Util.Companion.clickItemDelay(v, 3000);
                    Util.Companion.playSound();
//                    if(groupValueList.size() > 0) {
                    ArrayList<BleRssiDevice> bleDeviceList = new ArrayList<>();
                    for (int i = 0; i < groupValueList.size(); i++) {
                        bleDeviceList.add(groupValueList.get(i).getBleRssiDevice());
                    }
                    EventBus.getDefault().post(new ConnectEvent(EStep.STEP_SELECT_DEVICE.getData(), groupKey.getType(), groupKey.getId(), bleDeviceList));    //发送组连接事件统一处理业务
                }
            });

            //组条目点击事件
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    LogUtil.e("点击了group");

                    Util.Companion.playSound();
                    for (int i = 0; i < mBleGroupList.size(); i++) {
                        if (mBleGroupList.get(i).getConnectKey().getId() == (groupKey.getId())) {
                            if (mExpandableListView.isGroupExpanded(i)) {
                                mExpandableListView.collapseGroup(i);
                            } else {
                                mExpandableListView.expandGroup(i, true);
                            }
                        } else {
                            mExpandableListView.collapseGroup(i);
                        }
                    }

                }
            });
        }

//        private void expand(final View v)
//        {
//            v.measure(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//            final int targetHeight = v.getMeasuredHeight();
//            v.getLayoutParams().height = 0;
//            v.setVisibility(VISIBLE);
//
//            animation = new Animation()
//            {
//                @Override
//                protected void applyTransformation(float interpolatedTime, Transformation t)
//                {
//                    if (interpolatedTime == 1)
//                        isOpened = true;
//                    v.getLayoutParams().height = (interpolatedTime == 1) ? LinearLayout.LayoutParams.WRAP_CONTENT : (int) (targetHeight * interpolatedTime);
//                    v.requestLayout();
//                }
//
//
//                @Override
//                public boolean willChangeBounds() {
//                    return true;
//                }
//            };
//            animation.setDuration(duration);
//            v.startAnimation(animation);
//        }
//
//        private void collapse(final View v) {
//            final int initialHeight = v.getMeasuredHeight();
//            animation = new Animation()
//            {
//                @Override
//                protected void applyTransformation(float interpolatedTime, Transformation t) {
//                    if(interpolatedTime == 1)
//                    {
//                        v.setVisibility(View.GONE);
//                        isOpened = false;
//                    }
//                    else{
//                        v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
//                        v.requestLayout();
//                    }
//                }
//
//                @Override
//                public boolean willChangeBounds() {
//                    return true;
//                }
//            };
//
//            animation.setDuration(duration);
//            v.startAnimation(animation);
//        }

        private void changeGroupSelector(ConnectKey groupKey) {
            if (groupKey.isSelect()) {
                ivGroupSelector.setImageResource(R.drawable.ic_select);
            } else {
                ivGroupSelector.setImageResource(R.drawable.ic_unselect);
            }
        }

//        public ImageView getIvSelector() {
//            return ivGroupSelector;
//        }
//
//        public void setIvSelector(ImageView ivSelector) {
//            this.ivSelector = ivSelector;
//        }
//
//        public TextView getTvGroupName() {
//            return tvGroupName;
//        }
//
//        public void setTvGroupName(TextView tvGroupName) {
//            this.tvGroupName = tvGroupName;
//        }
//
//        public TextView getTvSend() {
//            return tvSend;
//        }
//
//        public void setTvSend(TextView tvSend) {
//            this.tvSend = tvSend;
//        }


    }

    class ChildViewHolder {

        private ImageView ivChildSelector;
        private TextView tvChildName;
        private TextView tvChildAddress;
        private ImageView ivChildModify;
        private Switch switchCheck;

        ChildViewHolder(View view) {
            ivChildSelector = view.findViewById(R.id.ivChildSelector);
            tvChildName = view.findViewById(R.id.tvChildName);
            tvChildAddress = view.findViewById(R.id.tvChildAddress);
            ivChildModify = view.findViewById(R.id.ivChildModify);
            switchCheck = view.findViewById(R.id.switchCheck);
        }

        void setEvent(final ConnectGroup bleGroup, int childPos, View convertView) {
            final ConnectValue groupValue = bleGroup.getConnectValueList().get(childPos);
            changeChildSelector(groupValue);
            changeSwitch(groupValue);   //初始化的时候是否开关

            ivChildSelector.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    childISelctorClick(bleGroup.getConnectKey(), groupValue);
//                    traverseSelector(bleGroup.getGroupKey());
//
//                    if (groupValue.isSelect()) {
//                        ivSelector.setImageResource(R.drawable.ic_unselect);
//                    } else {
//                        ivSelector.setImageResource(R.drawable.ic_select);
//                    }
//                    groupValue.setSelect(!groupValue.isSelect());
//                    notifyDataSetChanged();
                }
            });

            switchCheck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    groupValue.setSend(isChecked);
                    BleUtil.Companion.updateGroupValueSend(groupValue.getBleRssiDevice(), isChecked);
                }
            });

            //点击修改设备别名
            ivChildModify.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ModifyDialogFrag.Companion.show(mFm,
                            groupValue.getBleRssiDevice().getBleAddress(),
                            groupValue.getBleRssiDevice().getBleName(),
                            groupValue.getBleRssiDevice().getDeviceAlias());
//                    EventBus.getDefault().post(new DeviceModifyEvent(GroupFrag.class.getSimpleName(), groupValue.getBleRssiDevice()));
                }
            });

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    childISelctorClick(bleGroup.getConnectKey(), groupValue);
                }
            });
        }

        private void childISelctorClick(ConnectKey groupKey, ConnectValue groupValue) {
            traverseSelector(groupKey);
            if (groupValue.isSelect()) {
                ivChildSelector.setImageResource(R.drawable.ic_unselect);
            } else {
                ivChildSelector.setImageResource(R.drawable.ic_select);
            }
            groupValue.setSelect(!groupValue.isSelect());
            notifyDataSetChanged();
        }

        private void changeChildSelector(ConnectValue groupValue) {
            if (groupValue.isSelect()) {
                ivChildSelector.setImageResource(R.drawable.ic_select);
            } else {
                ivChildSelector.setImageResource(R.drawable.ic_unselect);
            }
        }

        private void changeSwitch(ConnectValue groupValue) {
            switchCheck.setChecked(groupValue.isSend());
        }


//        public ImageView getIvSelector() {
//            return ivSelector;
//        }
//
//        public void setIvSelector(ImageView ivSelector) {
//            this.ivSelector = ivSelector;
//        }
//
//        public TextView getTvChildName() {
//            return tvChildName;
//        }
//
//        public void setTvChildName(TextView tvChildName) {
//            this.tvChildName = tvChildName;
//        }
//
//        public TextView getTvChildAddress() {
//            return tvChildAddress;
//        }
//
//        public void setTvChildAddress(TextView tvChildAddress) {
//            this.tvChildAddress = tvChildAddress;
//        }
    }
}


